<script lang="ts">
import { defineComponent, ref, watch, reactive } from "vue";
import { useStore } from "vuex";
import OSS from "ali-oss";
import type { FormInstance, FormRules } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
import { h } from "vue";
import { ElMessage } from "element-plus";
import LocalCache from "@/utils/cache";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";

import type { UploadFile } from "element-plus";
import { asyncFileToBase64 } from "@/hooks/file-base64";
import { bucketUpload } from "@/utils/webOss";
export default defineComponent({
  setup(props) {
    const store = useStore();
    const centerDialogVisible = ref(false);
    const ruleFormRef = ref<FormInstance>();
    const rules = reactive<FormRules>({
      nickname: [
        {
          required: true,
          message: "请输入用户名",
          trigger: "blur"
        },
        {
          min: 2,
          max: 12,
          message: "",
          trigger: "blur"
        }
      ],
      gender: [
        {
          required: true,
          message: "请选择性别",
          trigger: "change"
        }
      ],
      phone: [
        {
          required: true,
          message: "请输入电话号码",
          trigger: "blur"
        },
        {
          min: 11,
          max: 12,
          message: "Length should be 11 to 12",
          trigger: "blur"
        }
      ],
      identity: [
        {
          required: true,
          message: "请选择员工的身份",
          trigger: "change"
        }
      ]
    });
    const ruleForm = reactive({
      nickname: "",
      gender: "",
      phone: "",
      identity: "",
      desc: ""
    });
    const formSize = ref("default");
    // const fileList = ref<UploadUserFile[]>([
    //   {
    //     name: "food.jpeg",
    //     url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100"
    //   }
    // ]);
    // const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
    //   console.log(uploadFile, uploadFiles);
    // };
    // const handlePreview: UploadProps["onPreview"] = (file) => {
    //   console.log(file);
    //   // imageUrl.value = URL.createObjectURL(file.raw)
    //   // fileList.value = URL.createObjectURL(file.raw);
    // };
    // const changeFile = (file: any, fileList: any) => {
    //   console.log("file" + file);
    //   let formData = new FormData();
    //   let currentFile = fileList[0].raw;
    //   formData.append("currentFile", currentFile);
    //   // 派发请求到store
    //   store.dispatch("system/uploadAvatar", formData);
    // };
    const dialogImageUrl = ref("");
    const dialogVisible = ref(false);
    const disabled = ref(false);

    const handleRemove = (file: UploadFile) => {
      console.log(file);
    };

    const handlePictureCardPreview = (file: UploadFile) => {
      dialogImageUrl.value = file.url!;
      dialogVisible.value = true;
    };

    const handleSuccess = (file: UploadFile) => {
      console.log(file);
    };
    const resetForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      formEl.resetFields();
    };
    // const handleSuccess = (response, file, fileList) => {
    //   console.log(response, file, fileList);
    // };
    const uploadBpmn = (params: any) => {
      let bucketName = "reclaim-me"; // 桶名
      let dir = `images`;
      const file = params.file;
      ruleForm.desc = file;
      bucketUpload(
        params.file,
        (res: any) => {
          let temp = {
            name: res.attachment,
            url: res.aliyunAddress
          };
          params.onSuccess(temp);
        },
        (err: any) => {
          console.log(err);
        },
        bucketName,
        dir
      );
      // 文件对象
      // const formData = new FormData();
      // formData.append("file", file);
      // formData.append("file_name", file.name);

      // store.dispatch("system/uploadAvatarReq", ruleForm);
    };
    // 传表单
    const submitForm = async (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      await formEl.validate((valid, fields) => {
        if (valid) {
          console.log("submit!");
          console.log("文件上传" + ruleForm.desc);
          const formData = new FormData();
          formData.append("file", ruleForm.desc);
          // for (let item in ruleForm) {
          //   formData.append(item, ruleForm[item]);
          // }
          formData.append("nickname", ruleForm.nickname);
          formData.append("gender", ruleForm.gender);
          formData.append("phone", ruleForm.phone);
          formData.append("identity", ruleForm.identity);
          // 派发请求到store
          store.dispatch("system/postemployeedata", formData);
          centerDialogVisible.value = false;
        } else {
          console.log("error submit!", fields);
          ElMessage.error({
            message: h("p", null, [
              h("span", null, "表单填写"),
              h("i", { style: "color: teal" }, "错误")
            ])
          });
        }
      });
    };
    return {
      centerDialogVisible,
      rules,
      ruleForm,
      formSize,
      submitForm,
      // handleRemove,
      // handlePreview,
      // fileList,
      resetForm,
      ruleFormRef,
      handleRemove,
      handlePictureCardPreview,
      disabled,
      handleSuccess,
      uploadBpmn
    };
  }
});
</script>
<template>
  <div class="page-model">
    <el-dialog
      v-model="centerDialogVisible"
      title="新建员工"
      width="40%"
      center
      destroy-on-close
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="用户名" prop="nickname">
          <el-input v-model="ruleForm.nickname" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="ruleForm.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="ruleForm.phone" placeholder="请输入电话号码" />
        </el-form-item>
        <!-- <el-form-item label="身份" prop="identity">
          <el-checkbox-group v-model="ruleForm.identity">
            <el-checkbox label="超级管理员" name="type" />
            <el-checkbox label="员工管理员" name="type" />
            <el-checkbox label="订单管理员" name="type" />
            <el-checkbox label="商品管理员" name="type" />
          </el-checkbox-group>
        </el-form-item> -->
        <el-form-item label="身份" prop="identity">
          <el-select v-model="ruleForm.identity" placeholder="请选择身份">
            <el-option label="超级管理员" value="1" />
            <el-option label="员工管理员" value="2" />
            <el-option label="订单管理员" value="3" />
            <el-option label="商品管理员" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="照片">
          <!-- <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            action=""
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            list-type="picture"
            :limit="1"
            :before-upload="changeFile"
            :on-success="handleSuccess"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">小于 500kb 的 jpg/png 文件</div>
            </template>
          </el-upload> -->
          <el-upload
            action="#"
            list-type="picture-card"
            :on-success="handleSuccess"
            ref="uploadref"
            :auto-upload="true"
            :http-request="uploadBpmn"
          >
            <el-icon><Plus /></el-icon>

            <template #file="{ file }">
              <div>
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <el-icon><zoom-in /></el-icon>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleDownload(file)"
                  >
                    <el-icon><Download /></el-icon>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <el-icon><Delete /></el-icon>
                  </span>
                </span>
                <!-- <el-button
                  style="margin-left: 10px"
                  size="small"
                  type="success"
                  @click="submitUpload(file)"
                  >上传</el-button
                > -->
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            Create
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped></style>
